package org.ghost.springboot2.demo.producer;

import org.apache.commons.lang3.RandomUtils;
import org.ghost.springboot2.demo.common.constant.RabbitMqConstant;
import org.ghost.springboot2.demo.common.util.ChineseNameUtil;
import org.ghost.springboot2.demo.dto.OrderMessageDTO;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Correlation;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * @author Administrator
 */
@Component
public class Producer {
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * 定时发送消息
     */
    @Scheduled(fixedDelay = 5 * 1000)
    public void sendMessage() {
//        rabbitTemplate.convertAndSend(RabbitMqConstant.DEFAULT_EXCHANGE, RabbitMqConstant.DEFAULT_KEY,
//                new OrderMessageDTO(UUID.randomUUID().toString(), ChineseNameUtil.getChineseName(), RandomUtils.nextInt(1, 100))
//        );

        rabbitTemplate.convertAndSend(RabbitMqConstant.DEFAULT_EXCHANGE, RabbitMqConstant.DEFAULT_KEY, new OrderMessageDTO(UUID.randomUUID().toString(), ChineseNameUtil.getChineseName(), RandomUtils.nextInt(1, 100))
                , new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {
                        if (message != null) {
                            message.getMessageProperties().setHeader("userName", "hello");
                            message.getMessageProperties().setHeader("password", "123456");
                        }
                        return message;
                    }

                    @Override
                    public Message postProcessMessage(Message message, Correlation correlation) {
                        if (message != null) {
                            message.getMessageProperties().setHeader("userName", "hello");
                            message.getMessageProperties().setHeader("password", "123456");
                        }
                        return message;
                    }
                });
    }
}
